{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "mnist = input_data.read_data_sets('data/', one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NETWORK READY\n"
     ]
    }
   ],
   "source": [
    "# NETWORK TOPOLOGIES\n",
    "n_hidden_1 = 256 \n",
    "n_hidden_2 = 128 \n",
    "n_input    = 784 \n",
    "n_classes  = 10  \n",
    "\n",
    "# INPUTS AND OUTPUTS\n",
    "x = tf.placeholder(\"float\", [None, n_input])\n",
    "y = tf.placeholder(\"float\", [None, n_classes])\n",
    "    \n",
    "# NETWORK PARAMETERS\n",
    "stddev = 0.1\n",
    "weights = {\n",
    "    'w1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),\n",
    "    'w2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),\n",
    "    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev=stddev))\n",
    "}\n",
    "biases = {\n",
    "    'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n",
    "    'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n",
    "    'out': tf.Variable(tf.random_normal([n_classes]))\n",
    "}\n",
    "print (\"NETWORK READY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def multilayer_perceptron(_X, _weights, _biases):\n",
    "    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1'])) \n",
    "    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2']))\n",
    "    return (tf.matmul(layer_2, _weights['out']) + _biases['out'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FUNCTIONS READY\n"
     ]
    }
   ],
   "source": [
    "# PREDICTION\n",
    "pred = multilayer_perceptron(x, weights, biases)\n",
    "\n",
    "# LOSS AND OPTIMIZER\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) \n",
    "optm = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost) \n",
    "corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))    \n",
    "accr = tf.reduce_mean(tf.cast(corr, \"float\"))\n",
    "\n",
    "# INITIALIZER\n",
    "init = tf.global_variables_initializer()\n",
    "print (\"FUNCTIONS READY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 003/020 cost: 2.269114979\n",
      "TRAIN ACCURACY: 0.190\n",
      "TEST ACCURACY: 0.250\n",
      "Epoch: 007/020 cost: 2.233587230\n",
      "TRAIN ACCURACY: 0.380\n",
      "TEST ACCURACY: 0.368\n",
      "Epoch: 011/020 cost: 2.194513177\n",
      "TRAIN ACCURACY: 0.360\n",
      "TEST ACCURACY: 0.458\n",
      "Epoch: 015/020 cost: 2.149544148\n",
      "TRAIN ACCURACY: 0.460\n",
      "TEST ACCURACY: 0.528\n",
      "Epoch: 019/020 cost: 2.096397300\n",
      "TRAIN ACCURACY: 0.530\n",
      "TEST ACCURACY: 0.593\n",
      "OPTIMIZATION FINISHED\n"
     ]
    }
   ],
   "source": [
    "training_epochs = 20\n",
    "batch_size      = 100\n",
    "display_step    = 4\n",
    "# LAUNCH THE GRAPH\n",
    "sess = tf.Session()\n",
    "sess.run(init)\n",
    "# OPTIMIZE\n",
    "for epoch in range(training_epochs):\n",
    "    avg_cost = 0.\n",
    "    total_batch = int(mnist.train.num_examples/batch_size)\n",
    "    # ITERATION\n",
    "    for i in range(total_batch):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "        feeds = {x: batch_xs, y: batch_ys}\n",
    "        sess.run(optm, feed_dict=feeds)\n",
    "        avg_cost += sess.run(cost, feed_dict=feeds)\n",
    "    avg_cost = avg_cost / total_batch\n",
    "    # DISPLAY\n",
    "    if (epoch+1) % display_step == 0:\n",
    "        print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost))\n",
    "        feeds = {x: batch_xs, y: batch_ys}\n",
    "        train_acc = sess.run(accr, feed_dict=feeds)\n",
    "        print (\"TRAIN ACCURACY: %.3f\" % (train_acc))\n",
    "        feeds = {x: mnist.test.images, y: mnist.test.labels}\n",
    "        test_acc = sess.run(accr, feed_dict=feeds)\n",
    "        print (\"TEST ACCURACY: %.3f\" % (test_acc))\n",
    "print (\"OPTIMIZATION FINISHED\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
